package com.struts2.service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.hibernate.HibernateUtil;
import com.struts2.model.Designer;

public class RegService {
	
	public String verifyReg(Designer designer){
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		
		int countuser = 0;
		int countname = 0;
		int countphone = 0;
		String result = "ok";
		
		String hqluser = "SELECT d.username FROM Designer d"
				+	" where d.username = :username";
		
		Query queryuser = session.createQuery(hqluser);
		queryuser.setString("username", designer.getUsername());
		
		for(@SuppressWarnings("rawtypes")
		Iterator it = queryuser.iterate(); it.hasNext();) {
			it.next();
			countuser++;
		}
		
		session.getTransaction().commit();
		
		session.beginTransaction();
		String hqlname = "SELECT d.name FROM Designer d"
				+	" where d.name = :name";
		
		Query queryname = session.createQuery(hqlname);
		queryname.setString("name", designer.getName());
		
		for(@SuppressWarnings("rawtypes")
		Iterator it = queryname.iterate(); it.hasNext();) {
			it.next();
			countname++;
		}
		
		session.getTransaction().commit();
		
		session.beginTransaction();
		String hqlpn = "SELECT d.phone_number FROM Designer d"
				+	" where d.phone_number = :phone_number";
		
		Query querypn = session.createQuery(hqlpn);
		querypn.setInteger("phone_number", designer.getPhone_number());
		
		for(@SuppressWarnings("rawtypes")
		Iterator it = querypn.iterate(); it.hasNext();) {
			it.next();
			countphone++;
		}
		
		session.getTransaction().commit();
		session.close();
		if (countuser != 0) {
			result = result + "u";
		}
		if (countname != 0) {
			result = result + "n";
		}
		if (countphone != 0) {
			result = result + "p";
		}
		return result;
	}
	
	public void insertDesigner(Designer designer) throws ParseException{
		Date date = new SimpleDateFormat("mm/dd/yyyy").parse(designer.getDobTemp());
		designer.setDob(date);
		System.out.println(date);
		
		designer.setApproval(false);
		
		if(designer.getType().equals("Group")){
			designer.setAddress("");
			designer.setGender("");
			designer.setEducation("");
		}
		
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		
		session.save(designer);
		
		session.getTransaction().commit();
		session.close();
		
		
		System.out.println("insert reg called");
		System.out.println(designer.getName());
		System.out.println(designer.isApproval());
	}
}
